<?php
class sessionHandler{
	private $db;
	public $expiry_time = 1800;

	public function __construct(&$db){
		if( empty($db) ){
			$this->error = 'Could not find the database';
			return false;
		}
		$this->db = $db;	
	}

	// called by session_start()
	public function open($save_path,$session_name){
		return true;
	}	
	
	// called at page end
	public function close(){
		return true;
	}

	// called after session_start()
	public function read($id){
		$rs = $this->db->where("id='$id' AND expiry_time>=".time())->get_one();	
		return $rs['data'];
	}

	// called when session data is to be written
	public function write($id,$data){
		$input = array();
		$input['expiry_time'] = time() + $this->expiry_time;		
		$input['data'] = $data;
		$input['id'] = $id;
		$input['ip'] = '0';
		$rs = $this->db->value($input)->replace();
		return $rs;
	}
	
	// called by session_destory()
	public function destory($id){
		return $this->db->where("id=$kd")->del();
	}

	// called randomly
	public 	function gc($maxlifetime){
		return $this->db->where("expiry_time<".time())->del();
	}
}
session_module_name();
$model = new Model('session');
$handler = new sessionHandler($model);
session_set_save_handler(
	array(&$handler, 'open'),
	array(&$handler, 'close'),
	array(&$handler, 'read'),
	array(&$handler, 'write'),
	array(&$handler, 'destory'),
	array(&$handler, 'gc')
);
// the following prevents unexpected effects when using objects as save handlers
//register_shutdown_function('session_write_close');
session_start();
